package com.zcxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcxx.common.PageInfo;
import com.zcxx.common.Result;
import com.zcxx.mapper.UserMapper;
import com.zcxx.model.User;
import com.zcxx.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;

    // 根据用户名查询用户
    @Override
    public User findByUsername(String username) {
        return getOne(new QueryWrapper<User>().eq("username", username));
    }

    // 根据邮箱查询用户
    @Override
    public User findByEmail(String email) {
        return getOne(new QueryWrapper<User>().eq("email", email));
    }

    // 注册
    @Override
    public String register(User user) {
        if (findByUsername(user.getUsername()) != null) {
            return "用户名已存在";
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));// 密码加密
        boolean saved = save(user);
        if (saved) {
            return "注册成功";
        } else {
            return "注册失败";
        }
    }

    // 密码匹配
    @Override
    public boolean matchesPassword(String password, String password1) {
        return passwordEncoder.matches(password, password1);
    }
}
